package com.attcatstudy.Thread;

import java.util.Random;
import java.util.concurrent.*;

import static java.lang.Thread.sleep;

/**
 * @author attcat
 * ---做一个有趣的程序员
 * @date 2022-10-29 14:13
 * @description  java中实现线程有几种方式?
 */
public class ThreadKinds {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadKinds threadKinds=new ThreadKinds();
        threadKinds.Mode1();
        threadKinds.Mode2();
        threadKinds.Mode3();
        threadKinds.Mode4();
    }

    //方式1:使用 Thread类或继承Thread类
    public void Mode1 () throws InterruptedException {
        Thread thread=new Thread(){
          public void run(){
              System.out.println("执行Mode1");
          }
        };
        sleep(1222);

        thread.start();
    }

    //实现 Runnable 接口配合Thread 把【线程】和【任务】(要执行的代码)分开
    //Thread 代表线程
    //Runnable 可运行的任务(线程要执行的代码)
    public void Mode2 () throws InterruptedException {
      Runnable runnable=new Runnable() {
          @Override
          public void run() {
              System.out.println("我要执行的方法2");
          }
      };
        Thread thread=new Thread(runnable,"线程1");
        sleep(1222);
        thread.start();
    }

    //使用有返回值的 Callable
    class CallableTask implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            System.out.println("我执行了call3");
            return new Random().nextInt(10);
        }
    }

    public void Mode3 () throws ExecutionException, InterruptedException {
        //创建线程池
        ExecutorService service= Executors.newFixedThreadPool(10);
        //提交任务，并用 Future提交返回结果
        Future<Integer> future=service.submit(new CallableTask());
        //打印返回值
        System.out.println( future.get());
        //停止线程
        if(!service.isShutdown()){
            service.shutdown();
        }




    }

    //方式4:使用 lambda
    public void Mode4 (){
        new Thread(()->{
            System.out.println("运行了4");
        }
         ).start();
    }


}
